#!/bin/bash
# Create database and user with secure password
#
# Author: Gary Locke
#
# Usage: Just run the damn script.
#
# To do:
#  - Check that user doesn't already exist.


# User check.
if [[ `whoami` != "root" ]];then
    echo "You are not root."; exit 1
fi

# MySQL server check.
db_check=`awk '/^127/ && /dbserver/' /etc/hosts 2>&1`
if [[ -z "$db_check" ]];then
    read -p "dbserver does not resolve to 127.0.0.1. Continue? [y/N]: " cont
    if [[ ! "$cont" =~ [Yy] ]];then
        echo "Exiting..."; exit 1
    fi
fi

# MySQL CLI client check.
if ! command -v mysql 2>&1 1>/dev/null;then
    echo "MySQL client not found by running 'mysql'. Exiting.."; exit 1
fi

# MySQL connection check.
if ! mysql -e ";" 2>/dev/null;then
    stty -echo; read -p "Enter root MySQL password[blank to quit]: " mysqlpass;echo;stty echo
    if [[ ! -z "$mysqlpass" ]];then
        pw_attempts=0
        while ! mysql -p$mysqlpass -e ";" 2>/dev/null; do
            pw_attempts=$((pw_attempts+1))
            if [[ "$pw_attempts" < 3 ]];then
                stty -echo; read -p "Try again: " mysqlpass;echo;stty echo
            else
                echo "Stop trying to brute force MySQL!"; exit 1
            fi
        done
    else
        echo "Quitting.."; exit 1
    fi
    pw_option="-p$mysqlpass"
fi

printf "Connected to MySQL..\n\n"

# Read in database name.
while true;do
    read -p "Enter database name: " dbname
    if [[ ! "$(mysql $pw_option -e "show databases like '$dbname';" --batch|egrep -vi '(^Database)')" =~ ^$dbname$ ]];then
        break
    else
        echo "Database $dbname already exists."
    fi
done

# Read in username.
    read -p "Enter username[same as db]: " username
if [[ -z "$username" ]];then
    username=$dbname
fi

# Read in hostname.
read -p "Enter source IP for new user[localhost]: " hostname
if [[ -z "$hostname" ]];then
    hostname=localhost
fi

# Check for firewall access if hostname is not localhost.
host_md5=`echo "$hostname"|md5sum|awk '{print $1}'`
localhost_md5=`echo "localhost"|md5sum|awk '{print $1}'`
if [[ "$host_md5" != "$localhost_md5" ]];then
    open_to_world=`iptables-save|grep 3306|egrep -v "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"`
    if [[ ! -z "$open_to_world" ]];then
        echo -e "\033[1;31miWarning: MySQL appears to be open to the world! Yikes!\033[0m"; sleep 3
    else
        open_to_host=`iptables-save|grep 3306|grep $hostname`
        if [[ -z "$open_to_host" ]]; then
            read -p "I don't see a firewall rule to open port 3306 to $hostname, add one? " add_iptables_rule
            case $add_iptables_rule in
                [yY] | [yY][Ee][Ss] )
                    read -p "Enter a comment for the rule: " comment
                    iptadd $hostname 3306 "$comment" 2>&1 1>/dev/null
                    ;;
                *)
                    echo "Exiting.."
                    exit 1
                    ;;
            esac
        fi
    fi
fi

# Read in password.
read -p "Enter password[random]: " password
if [[ -z "$password" ]];then
    password=`cat /dev/urandom| tr -dc "a-zA-Z0-9" | fold -w 20 |head -1`
fi

# Create database and user account.
mysql $pw_option -e "create database $dbname; grant all on $dbname.* to $username@$hostname identified by '$password'; flush privileges;"

# Print credentials for customer.
echo -e "\n\033[1;32mDatabase: $dbname"
if [[ "$hostname" == "localhost" ]];then
    echo -e "\033[1;32mUsername: $username"
else
    echo -e "\033[1;32mUsername: $username@$hostname"
fi
echo -e "\033[1;32mPassword: $password\033[0m\n"

mysql -u $username -p$password -e "show databases;" 2>&1 >/dev/null && echo -e "\033[1;32mTested OK.\033[0m\n" || echo -e "\033[1;31mCould not connect!\033[0m\nManually verify that the account works before updating the customer!\n"

exit 0
